package com.feishi.project.websocket.websocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * @version 1.0
 * @auth caixq
 * @time 18-5-3 09:36
 **/
@ServerEndpoint(value = "/imgbuffer")
@Component
public class OpenCv {
    private static Set<Session> sessionSet=new HashSet<>();

    private  static ObjectMapper objectMapper=new ObjectMapper();
    private Session session;

    @OnOpen
    public void onOpen(Session session) {
        this.session=session;
        sessionSet.add(session);
    }
    @OnClose
    public void onClose() {
        sessionSet.remove(this.session);
    }
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);
    }
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }


    public static void sendMessage(Session session,String message)  {
        if(!session.isOpen()){
            sessionSet.remove(session);
        }

        try {
            session.getBasicRemote().sendText(message);
        }catch (Exception e){
            e.printStackTrace();
            sessionSet.remove(session);
        }
    }
    public static void broadcast(Object object) throws IOException {
        String msg=objectMapper.writeValueAsString(object);
        for (Session session : sessionSet) {
            sendMessage(session,msg);

        }
    }

}
